<template>
  <div>
    <WebSocket />
    <div id="container" ref="container" style="width: 100%; height: calc(100vh - 100px)">
      <el-form v-if="showForm" :model="dataWarehouse" class="floating-form" label-width="100px">
        <el-select
          v-model="value"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入小区关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          :multiple-limit="1"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left; margin-right: 15px;">{{ item.label }}</span>
            <span style="float: left;" @click="yet(item.value, 1)">
              <img src="http://47.99.102.63:8888/group1/M00/00/03/rBah6WanM_KAeXFTAAATBDgQDOA118.png"
                   style="width: 20px; height: 20px; margin-right: 15px;"
              />

            </span>
            <span style="float: right;" @click="yet(item.value, 2)">
              <img src="http://47.99.102.63:8888/group1/M00/00/03/rBah6WanQTGAAnIdAAASs9TaBi0722.png"
                   style="width: 20px; height: 20px; margin-right: 5px;"
              />
            </span>
          </el-option>
        </el-select>
        <p>实有小区: {{ dataWarehouse.districtNum }}</p>
        <p>实有人口: {{ dataWarehouse.populationNum }}</p>
        <p>实有设备: {{ dataWarehouse.securityFacilitiesNum }}</p>
        <p>实有房屋: {{ dataWarehouse.realEstateNum }}</p>
        <p>实有车辆: {{ dataWarehouse.vehicleNum }}</p>
        <div ref="pieChartRef" class="chartRefs" style="width: 100%; height: 50%;"></div>
        <div ref="barChartRef" class="chartRefs2" style="width: 100%; height: 50%;"></div>
      </el-form>
      <el-popover
        ref="markerPopover"
        placement="bottom"
        :title="selectedMarker.communityName"
        width="400"
        trigger="manual"
        v-model="markerDialogVisible" class="markerPopover"
      >
        <el-form>
          <el-row :span="24">
            <el-col :span="10">
              <el-image :src="selectedMarker.image" style="width: 150px; height: 170px;"></el-image>
            </el-col>
            <el-col :span="10">
              <P style="color: #1359c5; font-size: 16px; font-weight: bold;">{{ selectedMarker.communityName }}</P>
              <p>{{ addresses }}</p>
              <P>所属辖区<span style="color: #325fa6;">{{ selectedMarker.name }}</span></P>
              <el-row :span="24">
                <el-col :span="10">
                  <p>居民楼</p>
                  <p><span style="color: #ef5400; font-size: 24px; font-weight: bold;"
                  >{{ districtCount.buildingCount }}</span>栋</p>
                </el-col>
                <el-col :span="10">
                  <p>住户</p>
                  <p><span style="color: #ef5400; font-size: 24px; font-weight: bold;"
                  >{{ districtCount.populationNum }}</span>户</p>
                </el-col>
              </el-row>
              <el-button @click="next(selectedMarker.id)" style="background: #1c84c6; color: #ffffff">进入小区
              </el-button>
            </el-col>
          </el-row>
          <el-row :span="24">
            <el-col :span="2">
              <i class="el-icon-video-camera-solid" style="font-size: 30px;"></i>
            </el-col>
            <el-col :span="4">
              <p>视频设备</p>
              <p><span style="color: #ef5400; font-size: 24px; font-weight: bold;">{{ districtCount.videoNum }}</span>个
              </p>
            </el-col>

            <el-col :span="2">
              <i class="el-icon-view" style="font-size: 30px;"></i>
            </el-col>
            <el-col :span="4">
              <p>人脸卡口</p>
              <p><span style="color: #ef5400; font-size: 24px; font-weight: bold;">{{ districtCount.faceNum }}</span>个
              </p>
            </el-col>

            <el-col :span="2">
              <i class="el-icon-truck" style="font-size: 30px;"></i>
            </el-col>
            <el-col :span="4">
              <p>车辆卡口</p>
              <p><span style="color: #ef5400; font-size: 24px; font-weight: bold;">{{ districtCount.vehicleNum }}</span>个
              </p>
            </el-col>

            <el-col :span="2">
              <i class="el-icon-key" style="font-size: 30px;"></i>
            </el-col>
            <el-col :span="4">
              <p>门禁设备</p>
              <p><span style="color: #ef5400; font-size: 24px; font-weight: bold;">{{ districtCount.doorNum }}</span>个
              </p>
            </el-col>
          </el-row>
        </el-form>
        <el-button @click="markerDialogVisible = false" type="primary" class="popoverButton">❌</el-button>
      </el-popover>
    </div>
    <div id="info"></div>
    <el-button @click="toggleFullScreen" class="toggleFullScreen">全屏</el-button>
    <el-button @click="openSearchDialog" class="search">搜索</el-button>
    <el-dialog
      title="搜索位置"
      :visible.sync="searchDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input
        placeholder="请输入地名"
        v-model="searchKeyword"
        @keyup.enter.native="searchLocation"
      >
        <el-button slot="append" icon="el-icon-search" @click="searchLocation"></el-button>
      </el-input>
      <div class="search-result" v-if="searchResult">
        <p>找到位置: {{ searchResult.name }}</p>
      </div>
    </el-dialog>
    <!-- 标记点信息弹窗 -->


  </div>
</template>
<script>
import { getList } from '@/api/community/StatisticsData'
import { estateCount, getDistrictCount, listDistricts, populationCount } from '@/api/community/district'
import WebSocket from '../../../components/WebSocket/websocket.vue'
import * as echarts from 'echarts'

export default {
  components: { WebSocket },

  data() {
    return {
      districtCount: {
        videoNum: 0,
        faceNum: 0,
        vehicleNum: 0,
        doorNum: 0,
        buildingCount: 0,
        populationNum: 0
      },
      addresses: '',
      selectedMarker: 0,
      markerDialogVisible: false,
      map: null, // 地图实例
      polygon: null, // 多边形覆盖物
      drawColor: '#CC16EF', // 绘制颜色
      areaPoint: [], // 存储多边形路径的数组
      showForm: true,
      districtList: [],
      dataWarehouse: {},
      locations: [], // 用于存储解析后的地址信息
      currentMarker: null, // 用于存储当前标记
      pieChart: null,
      barChart: null,
      pieOption: {
        tooltip: {
          trigger: 'none'
        },
        legend: false,
        series: [
          {
            label: {
              normal: {
                show: true, // 显示标签
                position: 'inside',
                formatter: '{b}: {d}%', // 格式化标签
                fontWeight: 'bold',
                fontSize: 13
              }
            },
            name: '人口统计',
            type: 'pie',
            radius: '100%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 1,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0,0,0,0.9)'
              }
            }
          }
        ]
      },
      barOption: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          position: function(pos, params, dom, rect, size) {
            return [size.viewSize[1] - 10, pos[1] - 30]; // 将 tooltip 显示在右侧
          }
        },
        xAxis: {
          type: 'value',
          position: 'bottom',
          axisLabel: {
            formatter: '{value} '
          }
        },
        yAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            formatter: function(value) {
              return value;
            },
            showMinLabel: true // 确保所有标签都显示
          }
        },
        series: [
          {
            name: '访问来源',
            type: 'bar',
            barWidth: '60%',
            data: [],
            label: {
              normal: {
                show: true,
                position: 'top'
              }
            }
          }
        ]
      },
      searchDialogVisible: false,
      searchKeyword: '',
      searchResult: null,
      options: [],
      value: [],
      list: [],
      loading: false,
      states: []
    }
  },
  name: 'Map',
  mounted() {
    this.initMap()
    this.updatePieChart();
    this.updateBarChart();
  },
  methods: {
    geocodeAddress(lnglat) {
      // 创建地理编码实例
      const geocoder = new AMap.Geocoder({
        radius: 1000, // 搜索范围
        extensions: 'all', // 返回地址的详细信息
        showbiz: false // 是否显示周边POI
      })

      // 解析经纬度字符串
      const [lng, lat] = lnglat.split(',').map(item => parseFloat(item.trim()))

      // 执行地理编码
      geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // 获取地址组件
          const addressComponent = result.regeocode.addressComponent
          // 构建详细地址字符串，只包含区和以下层级
          let detailedAddress = `${addressComponent.district || ''} ${addressComponent.township || ''} ${addressComponent.road || ''} ${addressComponent.number || ''}`.trim()

          // 如果详细地址不为空，则使用详细地址；否则，使用完整的格式化地址
          if (detailedAddress) {
            this.addresses = detailedAddress
          } else {
            this.addresses = result.regeocode.formattedAddress
          }

        } else {
          // 地理编码失败时的日志输出
          console.error('地理编码失败', status, result)
        }
      })
    },
    next(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    yet(value, type) {
      const item = this.options.find(option => option.value === value)
      if (item) {
        const centerPoint = item.value.split(':')[1]
        const id = item.value.split(':')[0]
        const latitude = parseFloat(centerPoint.split(',')[1])
        const longitude = parseFloat(centerPoint.split(',')[0])

        this.map.setZoomAndCenter(15, [longitude, latitude])
        this.newPoint(longitude, latitude)

        if (type === 2) {
          this.$router.push({
            path: '/community/population/' + id,
            name: 'Population',
            params: {
              id: id
            }
          })
        }
      }
      console.log(value, type)
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    initMap() {
      this.map = new AMap.Map('container', {
        zoom: 13,
        center: [116.397428, 39.90923],
        viewMode: '3D'
      })
      this.pieChart = echarts.init(this.$refs.pieChartRef)
      this.barChart = echarts.init(this.$refs.barChartRef)
      this.pieChart.setOption(this.pieOption)
      this.barChart.setOption(this.barOption)
      // 其他地图初始化代码...
      this.map.on('click', (e) => {
        this.newPoint(e.lnglat.lng, e.lnglat.lat)
      })
// 从后台获取区域数据
      this.getListDistrict()
    },
    newPoint(lng, lat) {
      if (this.currentMarker) {
        this.currentMarker.setMap(null)
      }
      this.currentMarker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        map: this.map,
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 确保 URL 是正确的
        size: new AMap.Size(24, 33),
        offset: new AMap.Pixel(-12, -33),
        title: '红色标记'
      })
    },
    onDraw(plats) {
      this.areaPoint = plats // 更新 paths 数组
      this.polygon = new AMap.Polygon({
        path: plats,
        strokeColor: '#FFF',
        strokeWeight: 3,
        fillColor: this.drawColor,
        fillOpacity: 0.5
      })
      this.map.add(this.polygon) // 将新多边形添加到地图上
    },

    addMarkersToMap() {
      this.districtList.forEach(item => {
        let marker = new AMap.Marker({
          position: new AMap.LngLat(item.centerPoint.split(',')[0], item.centerPoint.split(',')[1]),
          map: this.map,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
          size: new AMap.Size(24, 33),
          offset: new AMap.Pixel(-12, -33), // 根据图标实际大小调整偏移
          title: item.communityName
        })

        // 为标记点添加点击事件监听器
        AMap.event.addListener(marker, 'click', (e) => {
          // 此处的 e 是 AMap.Event 实例，不是浏览器事件，不能使用 stopPropagation
          // 设置当前选中的标记点
          this.selectedMarker = item
          this.geocodeAddress(item.centerPoint)
          this.getCount(item.id)
          // 显示 popover
          this.markerDialogVisible = true
          // 计算 popover 的位置
          let markerPos = e.target.getPosition() // 获取 marker 的经纬度位置
          let pixel = this.map.lngLatToContainer(markerPos) // 将经纬度转换为容器坐标

          // 使用 $nextTick 等待 DOM 更新
          this.$nextTick(() => {
            // 确保 markerPopover 已经挂载
            let popper = this.$refs.markerPopover.$el // 使用 $el 获取 popover 的 DOM 元素
            if (popper) {
              // 设置 popover 的位置
              popper.style.top = `${pixel.y - popper.offsetHeight}px`
              popper.style.left = `${pixel.x}px`
            }
          })
        })
      })
    },
    getCount(id) {
      getDistrictCount(id).then(res => {
        this.districtCount = res.data
        if (this.districtCount.doorNum == null) {
          this.districtCount.doorNum = 0
        }
        if (this.districtCount.populationNum == null) {
          this.districtCount.populationNum = 0
        }
        if (this.districtCount.buildingCount == null) {
          this.districtCount.buildingCount = 0
        }
        if (this.districtCount.videoNum == null) {
          this.districtCount.videoNum = 0
        }
        if (this.districtCount.faceNum == null) {
          this.districtCount.faceNum = 0
        }
        if (this.districtCount.vehicleNum == null) {
          this.districtCount.vehicleNum = 0
        }
      })
    },
    toggleFullScreen() {
      const mapContainer = this.$refs.container
      if (!document.fullscreenElement) {
        mapContainer.requestFullscreen().catch((e) => {
          console.error(`Error attempting to enable full-screen mode: ${e.message} (${e.name})`)
        })
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        }
      }
    },
    getListDistrict() {
      listDistricts(null).then(res => {
        this.districtList = res.rows
        this.addMarkersToMap()
        this.districtList.forEach(item => {
          var parse = JSON.parse(item.areaPoint)
          if (parse.length > 0) {
            this.onDraw(parse.map(p => new AMap.LngLat(p.lng, p.lat)))
          }
        })
        this.list = res.rows.map(item => {
          return { value: `${item.id + ':' + item.centerPoint}`, label: `${item.communityName}` }
        })
      })
    },
    getStatisticsData() {
      getList().then(res => {
        this.dataWarehouse = res.data
      })
    },
    openSearchDialog() {
      this.searchDialogVisible = true
      this.searchKeyword = ''
      this.searchResult = null
    },
    handleClose() {
      this.searchDialogVisible = false
    },
    searchLocation() {
      const _this = this
      AMap.plugin('AMap.Geocoder', () => {
        const geocoder = new AMap.Geocoder()
        geocoder.getLocation(_this.searchKeyword, (status, result) => {
          if (status == 'complete' && result.info == 'OK') {
            _this.searchResult = result.geocodes[0]
            _this.map.setZoomAndCenter(12, [_this.searchResult.location.getLng(), _this.searchResult.location.getLat()])
            _this.newPoint(_this.searchResult.location.getLng(), _this.searchResult.location.getLat())
          } else {
            _this.$message.error('未找到结果')
          }
          _this.searchDialogVisible = false
        })
      })
    },
    async updatePieChart() {
      // 获取数据
      const res = await populationCount();

      if (res.code === 200) {
        // 直接使用数据中的 populationTypeName
        const transformedData = res.data.map(item => ({
          value: item.totalPopulation,
          name: item.populationTypeName
        }));

        // 更新饼图数据
        this.pieOption.series[0].data = transformedData;

        // 检查 pieChart 是否已初始化
        if (this.pieChart) {
          // 应用新的配置项
          this.pieChart.setOption(this.pieOption);
        }
      }
    },

      async updateBarChart() {
        // 获取数据
        const res = await estateCount();

        if (res.code === 200) {
          // 提取数据
          const transformedData = res.data.map(item => ({
            value: item.realEstateTypeCount,
            name: item.estateType
          }));

          // 更新y轴数据
          this.barOption.yAxis.data = transformedData.map(item => item.name);

          // 更新series数据
          this.barOption.series[0].data = transformedData.map(item => item.value);

          // 更新图表
          if (this.barChart) {
            this.barChart.setOption(this.barOption);
          }
        }
      }
  },
  beforeDestroy() {
    if (this.pieChart) {
      this.pieChart.dispose()
    }
    if (this.barChart) {
      this.barChart.dispose()
    }
  },
  created() {
    this.getStatisticsData()
  }
}
</script>

<style> .custom-content-marker img {
  width: 100%;
  height: 100%;
}

.custom-content-marker .close-btn {
  position: absolute;
  top: -6px;
  right: -8px;
  width: 15px;
  height: 15px;
  font-size: 12px;
  background: #ccc;
  border-radius: 50%;
  color: #fff;
  text-align: center;
  line-height: 15px;
  box-shadow: -1px 1px 1px rgba(10, 10, 10, .2);
}

.floating-form {
  color: white;
  background-color: #1f2d3d;
  padding: 20px;
  z-index: 1000;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0.9;
  width: 200px;
  height: 100%;
}

.toggleFullScreen {
  position: absolute;
  left: 0;
  bottom: 0;
  z-index: 10000;
  background: #13ce66;
  color: #c03639;
}

.search {
  position: absolute;
  left: 80px;
  bottom: 0;
  z-index: 10000;
  background: #13ce66;
  color: #c03639;
}

.custom-content-marker .close-btn:hover {
  background: #666;
}

.chartRefs {
  position: relative;
  top: -80px; /* Adjust the position as needed */
}

.chartRefs2 {
  position: relative;
  top: -180px; /* Adjust the position as needed */
}

#container {
  position: relative; /* 确保容器是相对定位或绝对定位 */
}

.markerPopover {
  position: absolute; /* 确保popover是绝对定位 */
}

.popoverButton {
  position: absolute;
  top: 0;
  right: 0;
  background: #ffffff;
  border: 0 solid #ffffff;
}

.el-form p {
  margin-top: 0;
  margin-bottom: 5px; /* 调整这个值以减小间距 */
}
</style>
